/*
 * @lc app=leetcode.cn id=19 lang=java
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {

    /**
     * Accepted
    208/208 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 95.7 % of java submissions (39.3 MB)
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode l1 = dummy, l2 = dummy;
        int i = 0;
        while (l1 != null) {
            if (i < n + 1) {
                l1 = l1.next;
                i++;
            } else {
                l1 = l1.next;
                l2 = l2.next;
            }
        }
        l2.next = l2.next.next;
        return dummy.next;
    }
}
// @lc code=end
